package cn.wildfire.chat.app.extendsion.classes;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;

/**
 * Create by HEKE, 2019/8/21 16:30
 * TODO 控件是否可用倒计时控制对象
 */
public class ViewTimerSet {

    private static final int LOOPER_TAG = 1;
    private Context context;
    private TextView mView;

    /**
     * 倒计时60秒
     */
    private int count = 60;

    protected boolean timeoutFinished;

    private boolean forceEnd;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOOPER_TAG:
                    if (forceEnd) {
                        mView.setEnabled(true);
                        mView.setText(context.getString(R.string.send_sms_code));
                        timeoutFinished = true;
                        return;
                    }
                    mView.setText(count + "s");
                    count--;
                    if (count >= 0) {
                        mHandler.sendEmptyMessageDelayed(LOOPER_TAG, 1000);
                    } else {
                        mView.setEnabled(true);
                        mView.setText(context.getString(R.string.send_sms_code));
                        timeoutFinished = true;
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public ViewTimerSet(Context context, TextView view) {
        this.context = context;
        this.mView = view;
        this.timeoutFinished = false;
    }

    /**
     * 执行操作
     */
    public void run() {
        try {
            mView.setEnabled(false);
            mHandler.sendEmptyMessageDelayed(LOOPER_TAG, 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 倒计时是否结束
     */
    public boolean isTimeoutFinished() {
        return timeoutFinished;
    }


    /**
     * 强制中断
     */
    public void forceInterrupt() {
        forceEnd = true;
    }

}
